package org.jeecg.modules.salary.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.salary.entity.SalaryAdjust;
import org.jeecg.modules.salary.entity.SalaryFields;
import org.jeecg.modules.salary.service.ISalaryAdjustService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.salary.service.ISalaryFieldsService;
import org.jeecg.modules.salary.vo.AdjustVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 薪资调整
 * @Author: jeecg-boot
 * @Date:   2020-08-20
 * @Version: V1.0
 */
@Api(tags="薪资调整")
@RestController
@RequestMapping("/salary/salaryAdjust")
@Slf4j
public class SalaryAdjustController extends JeecgController<SalaryAdjust, ISalaryAdjustService> {
	@Autowired
	private ISalaryAdjustService salaryAdjustService;

	@Autowired
	private ISalaryFieldsService salaryFieldsService;
	
	/**
	 * 分页列表查询
	 *
	 * @param salaryAdjust
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "薪资调整-分页列表查询")
	@ApiOperation(value="薪资调整-分页列表查询", notes="薪资调整-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(SalaryAdjust salaryAdjust,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<SalaryAdjust> queryWrapper = QueryGenerator.initQueryWrapper(salaryAdjust, req.getParameterMap());
		queryWrapper.orderByDesc("create_time");
		Page<SalaryAdjust> page = new Page<SalaryAdjust>(pageNo, pageSize);
		IPage<SalaryAdjust> pageList = salaryAdjustService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	 /**
	  * 分页列表查询
	  *
	  * @param salaryAdjust
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "薪资调整-我的调薪分页列表查询")
	 @ApiOperation(value="薪资调整-我的调薪分页列表查询", notes="薪资调整-我的调薪分页列表查询")
	 @GetMapping(value = "/myList")
	 public Result<?> queryMyPageList(SalaryAdjust salaryAdjust,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 QueryWrapper<SalaryAdjust> queryWrapper = QueryGenerator.initQueryWrapper(salaryAdjust, req.getParameterMap());
		 queryWrapper.orderByDesc("create_time");
		 queryWrapper.eq("user_id",sysUser.getUsername());
		 Page<SalaryAdjust> page = new Page<SalaryAdjust>(pageNo, pageSize);
		 IPage<SalaryAdjust> pageList = salaryAdjustService.page(page, queryWrapper);
		 return Result.ok(pageList);
	 }
	
	/**
	 *   添加
	 *
	 * @param salaryAdjust
	 * @return
	 */
	@AutoLog(value = "薪资调整-添加")
	@ApiOperation(value="薪资调整-添加", notes="薪资调整-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody SalaryAdjust salaryAdjust) {
		String userId = salaryAdjust.getUserId();
		String fieldValue = "";
		double money = 0L;
		String adjustType = salaryAdjust.getAdjustType();
		String adjustValue = salaryAdjust.getAdjustValue();
		if(userId.contains(",")){
			String[] arr = userId.split(",");
			for(int i=0;i<arr.length;i++){
				SalaryAdjust salaryAdjustNew = new SalaryAdjust();
				salaryAdjustNew.setUserId(arr[i]);
				//获取调整前的最新值
				fieldValue = salaryFieldsService.getFieldValue(arr[i],salaryAdjust.getFieldId());
				salaryAdjustNew.setFieldDefaultOld(fieldValue);
				//1上调，2下调
				if(CommonConstant.STATUS_1.equals(adjustType)){
					money = Double.valueOf(fieldValue) + Double.valueOf(adjustValue);
					salaryAdjustNew.setFieldDefaultNew(String.valueOf(money));
				}else{
					money = Double.valueOf(fieldValue) - Double.valueOf(adjustValue);
					salaryAdjustNew.setFieldDefaultNew(String.valueOf(money));
				}
				salaryAdjustNew.setAdjustType(adjustType);
				salaryAdjustNew.setAdjustValue(adjustValue);
				salaryAdjustNew.setFieldId(salaryAdjust.getFieldId());
				salaryAdjustNew.setAdjustReason(salaryAdjust.getAdjustReason());
				salaryAdjustService.save(salaryAdjustNew);
			}
			return Result.ok("添加成功！");
		}
		salaryAdjustService.save(salaryAdjust);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param salaryAdjust
	 * @return
	 */
	@AutoLog(value = "薪资调整-编辑")
	@ApiOperation(value="薪资调整-编辑", notes="薪资调整-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody SalaryAdjust salaryAdjust) {
		salaryAdjustService.updateById(salaryAdjust);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "薪资调整-通过id删除")
	@ApiOperation(value="薪资调整-通过id删除", notes="薪资调整-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		salaryAdjustService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "薪资调整-批量删除")
	@ApiOperation(value="薪资调整-批量删除", notes="薪资调整-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.salaryAdjustService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "薪资调整-通过id查询")
	@ApiOperation(value="薪资调整-通过id查询", notes="薪资调整-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		SalaryAdjust salaryAdjust = salaryAdjustService.getById(id);
		if(salaryAdjust==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(salaryAdjust);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param salaryAdjust
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SalaryAdjust salaryAdjust) {
        return super.exportXls(request, salaryAdjust, SalaryAdjust.class, "薪资调整");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SalaryAdjust.class);

    }

	 /**
	  * 根据fieldId和userID查询项目的最新值
	  *
	  * @param fieldId
	  * @return
	  */
	 @AutoLog(value = "薪资调整-通过FileCode和userID查询")
	 @ApiOperation(value="薪资调整-通过FileCode和userID查询", notes="薪资调整-通过FileCode和userID查询")
	 @GetMapping(value = "/queryByFieldId")
	 public Result<?> queryByFileCode(@RequestParam(name="fieldId",required=true)  String fieldId,
									  @RequestParam(name="userId",required=true)  String userId) {

		 String fieldValue = salaryFieldsService.getFieldValue(userId,fieldId);
		 return Result.ok(fieldValue);
	 }



	 @AutoLog(value = "薪资调整-返回字段值")
	 @ApiOperation(value="薪资调整-返回字段值", notes="薪资调整-返回字段值")
	 @GetMapping(value = "/dicCode")
	 public Result<?>  dicCode() {
	 	List<AdjustVo> list = new ArrayList<>();
	 	LambdaQueryWrapper<SalaryFields> queryWrapper = new  LambdaQueryWrapper();
	 	queryWrapper.isNull(SalaryFields::getDeletedAt);
	 	queryWrapper.eq(SalaryFields::getHasChildren,CommonConstant.STATUS_0);
	 	queryWrapper.eq(SalaryFields::getFieldDefaultSet,CommonConstant.STATUS_1);
	 	List<SalaryFields> salaryFieldsList = salaryFieldsService.list(queryWrapper);
	 	for(SalaryFields fields:salaryFieldsList){
			AdjustVo adjustVo = new AdjustVo();
			adjustVo.setValue(fields.getId());
			adjustVo.setText(fields.getFieldName());
			adjustVo.setTitle(fields.getFieldName());
			list.add(adjustVo);
		}
	 	return Result.ok(list);
	 }

}
